package com.ncbee.base.service.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ncbee.base.dao.UserDao;
import com.ncbee.base.dao.UserRoleDao;
import com.ncbee.base.model.entity.Resource;
import com.ncbee.base.model.entity.User;
import com.ncbee.base.model.entity.UserRole;
import com.ncbee.base.model.vo.BaseQuery;
import com.ncbee.base.model.vo.UserInfo;
import com.ncbee.base.model.vo.tableVo.ResourceVo;
import com.ncbee.base.model.vo.tableVo.UserVo;
import com.ncbee.base.service.BaseDataService;
import com.ncbee.base.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author youdianyun
 * @since 2018-11-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private BaseDataService baseDataService;


    @Override
    public IPage<UserVo> getUserList(IPage<UserVo> page, BaseQuery<User> baseQuery){
        return baseMapper.selectUserList(page,baseQuery);
    }

    @Override
    @CacheEvict(value="userAllResource",key="#userId")
    public boolean grantRoleToUser(Long userId, String roleStr) {
        //delete old user role
        Map<String,Object> param= new HashMap<String,Object>();
        param.put("user_id",userId);
        int rows=userRoleDao.deleteByMap(param);
        logger.info("----删除用户原有所有角色总计"+rows+"条记录-----");
        int realNum=0;
        int expectNum=0;
        List<UserRole> userRoleList=null;
        Map<String,Object> addParam=new HashMap<String,Object>();//添加参数
        if(!StringUtils.isEmpty(roleStr)){//分配的角色不为空
            userRoleList=new ArrayList<UserRole>();
            String roleIdArray[]=roleStr.split(",");
            expectNum=roleIdArray.length;
            for(int i=0;i<roleIdArray.length;i++){
                UserRole userRole=new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(Long.parseLong(roleIdArray[i]));
                userRole.setCreateTime(LocalDateTime.now());
                userRoleList.add(userRole);
            }
        }
        if(userRoleList!=null){
          realNum=userRoleDao.batchSave(userRoleList);
        }

        return (realNum==expectNum);
    }

    @Override
    public UserInfo userLogin(String username, String password){
        List<UserInfo> userInfoList=this.baseMapper.selectUserInfoByUsername(username);

        if(CollectionUtils.isEmpty(userInfoList)){
            return null;
        }else{
            return userInfoList.get(0);
        }
    }

    /**
     *  通过用户ID查询
     *  用户所有拥有的权限
     * @param id
     * @return
     */
    @Cacheable(value="userAllResource",key="#id")
    @Override
    public List<Resource> getUserAllResourceById(Long id) {
        return this.baseMapper.selectUserResourceById(id);
    }

    @Override
    public List<ResourceVo> getUserMenuResource(Long id) {
        return this.baseMapper.selectUserMenuById(id);
    }

    @Override
    public boolean resetUserPassword(Long userId){
        String defaultUserPassword=baseDataService.getBaseDataValueByNodeCode("CZMM");
        if(StringUtils.isEmpty(defaultUserPassword)){
            defaultUserPassword="000000";//如果基础数据表中不存在该数据则默认为 000000  六个0
        }
        User user=getById(userId);
        user.setPassword(com.ncbee.base.util.StringUtils.getCustomMD5Str(defaultUserPassword));
        user.setUpdateTime(LocalDateTime.now());
        return updateById(user);
    }

    /**
     * 更新用户密码
      * @param userId
     * @param password
     * @return
     */
    @Override
    public boolean updateUserPassword(Long userId,String password) {
        User user=this.getById(userId);
        user.setPassword(com.ncbee.base.util.StringUtils.getCustomMD5Str(password));
        user.setUpdateTime(LocalDateTime.now());
        return updateById(user);
    }
}
